import React from "react"
import Taro from "@tarojs/taro"
import { ScrollView, View } from "@tarojs/components"
import { Cell, DropdownMenu, Search, /** Button, **/ Sticky } from "@taroify/core"
import { Success } from "@taroify/icons"
import GpContainer from "@/components/GpContainer"
import GpIntroBadgeItem from "@/components/GpIntroBadgeItem"
import GpJumpNavs from "@/components/GpJumpNavs"
import GpCurrentPort from "@/components/GpCurrentPort"
import GpSimpleTabbar from "@/components/GpSimpleTabbar"
import { cloneDeep, setPageMeta } from "@/utils/common"
import clsx from "clsx"
import { getBadgeFilters, getBadgeList } from "@/apis/index"
import { NO_RESTRICT } from "@/constants/words"
import GpEmpty from "@/components/GpEmpty"
import styles from "@/styles/common/top-fixed.module.scss"
import myStyles from "./index.module.scss"
import GpScrollLoading from "@/components/GpScrollLoading"

const iconSize = Taro.pxTransform(20)
const ports = [{ text: "招生简章" }]
type IState = {
  /** 过滤面板所选择的过滤项 */
  selectedFilterKey: any
  /** 所在地区列表省份 */
  provinceOptions: IDropDownFilterOption[]
  /** 年份 */
  yearOptions: IDropDownFilterOption[]
  /** 学历层次 */
  levelOptions: IDropDownFilterOption[]
  /** 院校特色 */
  featureOptions: IDropDownFilterOption[]
  keyword: string
  pagination: IPagination
  list: any[]
  showLoading: boolean
}
type IData = {
  pristine_provinceOptions: IDropDownFilterOption[]
  pristine_yearOptions: IDropDownFilterOption[]
  pristine_levelOptions: IDropDownFilterOption[]
  pristine_featureOptions: IDropDownFilterOption[]
  pageMeta: {
    yearString: string
    pageLoaded: boolean
    areaString: string
  }
}
/** 招生简章 */
class IntroBadge extends React.Component<unknown, IState> {
  extData: IData
  constructor(props) {
    super(props)
    this.state = {
      selectedFilterKey: false,
      provinceOptions: [],
      yearOptions: [],
      levelOptions: [],
      featureOptions: [],
      keyword: "",
      pagination: {
        page: 1,
        pageCount: 1
      },
      list: [],
      showLoading: true
    }
    this.extData = {
      pristine_provinceOptions: [],
      pristine_yearOptions: [],
      pristine_levelOptions: [],
      pristine_featureOptions: [],
      pageMeta: {
        yearString: "",
        pageLoaded: false,
        areaString: ""
      }
    }
  }
  onShareAppMessage() {}
  onLoad() {
    this.getFilterOptions()
    this.search(1)
  }
  componentDidShow() {
    this.setPageInfo()
  }
  setPageInfo = () => {
    const { pageLoaded, yearString, areaString } = this.extData.pageMeta
    if (pageLoaded) {
      setPageMeta({
        keywords: `${yearString}${areaString}院校艺术招生简章，${yearString}${areaString}院校艺考招生新闻`,
        title: `${yearString}各大院校艺考招生简章--各大艺术院校报名时间与条件-择艺宝`,
        description: `择艺宝为你整理${yearString}各大院校艺考招生简章，其中包含报名时间、报名条件、报名方式、志愿填报、录取方式等相关信息`
      })
    }
  }
  getPageInfo = (years: number[], provinceNames: string[]) => {
    if (years.length > 0) {
      this.extData.pageMeta.yearString = years[0] + "年"
    } else {
      this.extData.pageMeta.yearString = ""
    }
    if (provinceNames.length > 0) {
      this.extData.pageMeta.areaString = provinceNames[0]
    } else {
      this.extData.pageMeta.areaString = ""
    }
    this.extData.pageMeta.pageLoaded = true
    this.setPageInfo()
  }
  getFilterOptions = () => {
    getBadgeFilters().then(res => {
      if (res.data.success) {
        const retData = res.data.data
        const provinceOptions: IDropDownFilterOption[] = (retData.provinceOptions || []).map(l => {
          return {
            text: l.label,
            value: l.value
          }
        })
        provinceOptions.unshift({
          text: NO_RESTRICT.text,
          value: NO_RESTRICT.value
        })
        const yearOptions: IDropDownFilterOption[] = (retData.yearOptions || []).map(l => {
          return {
            text: l.label,
            value: l.value
          }
        })
        yearOptions.unshift({
          text: NO_RESTRICT.text,
          value: NO_RESTRICT.value
        })
        const levelOptions: IDropDownFilterOption[] = (retData.levelOptions || []).map(l => {
          return {
            text: l.label,
            value: l.value
          }
        })
        levelOptions.unshift({
          text: NO_RESTRICT.text,
          value: NO_RESTRICT.value
        })
        const featureOptions: IDropDownFilterOption[] = (retData.featureOptions || []).map(l => {
          return {
            text: l.label,
            value: l.value
          }
        })
        featureOptions.unshift({
          text: NO_RESTRICT.text,
          value: NO_RESTRICT.value
        })
        this.setState({
          provinceOptions,
          yearOptions,
          levelOptions,
          featureOptions
        })
        this.extData.pristine_provinceOptions = cloneDeep(provinceOptions)
        this.extData.pristine_yearOptions = cloneDeep(yearOptions)
        this.extData.pristine_levelOptions = cloneDeep(levelOptions)
        this.extData.pristine_featureOptions = cloneDeep(featureOptions)
      }
    })
  }
  search = (page = 1, showLoading = true) => {
    if (showLoading) {
      Taro.showLoading()
    }
    const { provinceOptions, yearOptions, featureOptions, keyword, levelOptions } = this.state
    const provinceNames = [] as string[]
    const provinces = provinceOptions
      .filter(l => l.checked && l.value !== NO_RESTRICT.value)
      .map(l => {
        provinceNames.push(l.text)
        return l.value
      })
    const level = levelOptions
      .filter(l => l.checked && l.value !== NO_RESTRICT.value)
      .map(l => l.value)
    const years = yearOptions
      .filter(l => l.checked && l.value !== NO_RESTRICT.value)
      .map(l => l.value)
    const features = featureOptions
      .filter(l => l.checked && l.value !== NO_RESTRICT.value)
      .map(l => l.value)
    this.getPageInfo(years, provinceNames)
    return getBadgeList({
      search: {
        provinces,
        level: level[0],
        years,
        features,
        keyword
      },
      pagination: {
        current: page,
        pageSize: 10
      }
    })
      .then(res => {
        if (res.data.success) {
          const retData = res.data.data
          const retList = retData.list || []
          if (page === 1) {
            this.setState({
              list: retList
            })
          } else {
            this.setState({
              list: this.state.list.concat(retList)
            })
          }
          this.setState({
            pagination: {
              page: retData.pagination.current,
              pageCount: retData.pagination.pageCount
            },
            showLoading: retData.pagination.current + 1 <= retData.pagination.pageCount
          })
        }
      })
      .finally(() => {
        if (showLoading) {
          Taro.hideLoading()
        }
      })
  }
  handleDropdownMenuChange = (filterKey: any) => {
    this.setState({
      selectedFilterKey: filterKey
    })
  }
  unCheckedAll = (list: IDropDownFilterOption[]) => {
    list.forEach(l => {
      l.checked = false
    })
  }
  unCheckedNoRestrict = (list: IDropDownFilterOption[]) => {
    const finder = list.find(l => l.value === NO_RESTRICT.value)
    if (finder && finder.checked) {
      finder.checked = false
    }
  }
  handleClickAddress = (item: IDropDownFilterOption) => {
    const _list = cloneDeep(this.state.provinceOptions)
    const finder = _list.find(l => l.value === item.value)
    if (finder) {
      // 不限
      if (finder.value === NO_RESTRICT.value) {
        const toBeCheced = !finder.checked
        if (toBeCheced) {
          this.unCheckedAll(_list)
          finder.checked = toBeCheced
        } else {
          finder.checked = !finder.checked
        }
      } else {
        this.unCheckedNoRestrict(_list)
        finder.checked = !finder.checked
      }
      this.setState({
        provinceOptions: _list
      })
    }
  }
  handleClickAddress_single = (item: IDropDownFilterOption) => {
    const _list = cloneDeep(this.state.provinceOptions)
    const finder = _list.find(l => l.value === item.value)
    if (finder) {
      const toBeCheced = !finder.checked
      _list.forEach(l => {
        l.checked = false
      })
      finder.checked = toBeCheced
      this.setState(
        {
          provinceOptions: _list,
          selectedFilterKey: false
        },
        () => {
          this.search(1)
        }
      )
    }
  }
  handleClickLevel = (item: IDropDownFilterOption) => {
    const _list = cloneDeep(this.state.levelOptions)
    const finder = _list.find(l => l.value === item.value)
    if (finder) {
      const toBeCheced = !finder.checked
      _list.forEach(l => {
        l.checked = false
      })
      finder.checked = toBeCheced
      this.setState(
        {
          levelOptions: _list,
          selectedFilterKey: false
        },
        () => {
          this.search(1)
        }
      )
    }
  }
  handleClickYears = (item: IDropDownFilterOption) => {
    const _list = cloneDeep(this.state.yearOptions)
    const finder = _list.find(l => l.value === item.value)
    if (finder) {
      // 不限
      if (finder.value === NO_RESTRICT.value) {
        const toBeCheced = !finder.checked
        if (toBeCheced) {
          this.unCheckedAll(_list)
          finder.checked = toBeCheced
        } else {
          finder.checked = !finder.checked
        }
      } else {
        this.unCheckedNoRestrict(_list)
        finder.checked = !finder.checked
      }
      this.setState({
        yearOptions: _list
      })
    }
  }
  handleClickYears_single = (item: IDropDownFilterOption) => {
    const _list = cloneDeep(this.state.yearOptions)
    const finder = _list.find(l => l.value === item.value)
    if (finder) {
      const toBeCheced = !finder.checked
      _list.forEach(l => {
        l.checked = false
      })
      finder.checked = toBeCheced
      this.setState(
        {
          yearOptions: _list,
          selectedFilterKey: false
        },
        () => {
          this.search(1)
        }
      )
    }
  }
  handleClickFeature = (item: IDropDownFilterOption) => {
    const _list = cloneDeep(this.state.featureOptions)
    const finder = _list.find(l => l.value === item.value)
    if (finder) {
      // 不限
      if (finder.value === NO_RESTRICT.value) {
        const toBeCheced = !finder.checked
        if (toBeCheced) {
          this.unCheckedAll(_list)
          finder.checked = toBeCheced
        } else {
          finder.checked = !finder.checked
        }
      } else {
        this.unCheckedNoRestrict(_list)
        finder.checked = !finder.checked
      }
      this.setState({
        featureOptions: _list
      })
    }
  }
  handleClickFeature_single = (item: IDropDownFilterOption) => {
    const _list = cloneDeep(this.state.featureOptions)
    const finder = _list.find(l => l.value === item.value)
    if (finder) {
      const toBeCheced = !finder.checked
      _list.forEach(l => {
        l.checked = false
      })
      finder.checked = toBeCheced
      this.setState(
        {
          featureOptions: _list,
          selectedFilterKey: false
        },
        () => {
          this.search(1)
        }
      )
    }
  }
  onPullDownRefresh() {
    this.search(1, false).finally(() => {
      Taro.stopPullDownRefresh()
    })
  }
  onReachBottom() {
    const { pagination } = this.state
    if (pagination.page + 1 <= pagination.pageCount) {
      this.search(pagination.page + 1, false)
    }
  }
  handleKeywordChange = (ev: any) => {
    this.setState({
      keyword: ev.detail.value
    })
  }
  resetAddress = () => {
    this.setState(
      {
        provinceOptions: cloneDeep(this.extData.pristine_provinceOptions),
        selectedFilterKey: false
      },
      () => {
        this.search(1)
      }
    )
  }
  resetYears = () => {
    this.setState(
      {
        yearOptions: cloneDeep(this.extData.pristine_yearOptions),
        selectedFilterKey: false
      },
      () => {
        this.search(1)
      }
    )
  }
  resetFeatures = () => {
    this.setState(
      {
        featureOptions: cloneDeep(this.extData.pristine_featureOptions),
        selectedFilterKey: false
      },
      () => {
        this.search(1)
      }
    )
  }
  handleConfirm = () => {
    this.handleDropdownMenuChange(false)
    this.search(1)
  }
  /** 顶部filter */
  renderFixedFilter = () => {
    const {
      selectedFilterKey,
      provinceOptions,
      yearOptions,
      levelOptions,
      featureOptions,
      keyword
    } = this.state
    return (
      <View className={clsx(styles["top-fixed"], "bg-white")}>
        <View className="w-682px pt-32px mx-auto">
          <Search
            className={clsx(myStyles["top-search"], "top-search")}
            shape="round"
            placeholder="请输入搜索关键词"
            value={keyword}
            onChange={this.handleKeywordChange}
            onSearch={() => this.search(1)}
            clearable={false}
          />
        </View>
        <Sticky>
          {/* 下拉选择面板 */}
          <View catchMove>
            <DropdownMenu
              value={selectedFilterKey}
              onChange={this.handleDropdownMenuChange}
              className={clsx(
                styles["filter-dropdown"],
                myStyles["filter-dropdown"],
                "filter-dropdown"
              )}
            >
              <DropdownMenu.Item title="所在地区">
                <View className="flex-1 flex flex-col overflow-hidden">
                  <View className={myStyles["dropdown-list-content"]}>
                    <View className="flex-1">
                      <ScrollView
                        scrollY
                        style={{
                          height: "100%"
                        }}
                      >
                        {provinceOptions.map(l => (
                          <Cell
                            key={l.value}
                            title={l.text}
                            align="center"
                            clickable
                            onClick={() => this.handleClickAddress_single(l)}
                            className={clsx(styles["filter-dropdown-cell"], {
                              [styles["checked"]]: l.checked
                            })}
                          >
                            {l.checked && (
                              <Success
                                color="#1A8CFF"
                                style={{
                                  fontSize: iconSize
                                }}
                              />
                            )}
                          </Cell>
                        ))}
                      </ScrollView>
                    </View>
                  </View>
                  {/* <View className={styles["filter-opt"]}>
                    <Button
                      color="default"
                      style={{ color: "#666666" }}
                      className={styles["filter-opt-btn"]}
                      onClick={this.resetAddress}
                    >
                      重置
                    </Button>
                    <Button
                      style={{ backgroundColor: "#1A8CFF", color: "#fff" }}
                      className={styles["filter-opt-btn"]}
                      onClick={this.handleConfirm}
                    >
                      确认
                    </Button>
                  </View> */}
                </View>
              </DropdownMenu.Item>
              <DropdownMenu.Item title="所属年份">
                <View className="flex-1 flex flex-col overflow-hidden">
                  <View className={myStyles["dropdown-list-content"]}>
                    <View className="flex-1">
                      <ScrollView
                        scrollY
                        style={{
                          height: "100%"
                        }}
                      >
                        {yearOptions.map(l => (
                          <Cell
                            key={l.value}
                            title={l.text}
                            align="center"
                            clickable
                            onClick={() => this.handleClickYears_single(l)}
                            className={clsx(styles["filter-dropdown-cell"], {
                              [styles["checked"]]: l.checked
                            })}
                          >
                            {l.checked && (
                              <Success
                                color="#1A8CFF"
                                style={{
                                  fontSize: iconSize
                                }}
                              />
                            )}
                          </Cell>
                        ))}
                      </ScrollView>
                    </View>
                  </View>
                  {/* <View className={styles["filter-opt"]}>
                    <Button
                      color="default"
                      style={{ color: "#666666" }}
                      className={styles["filter-opt-btn"]}
                      onClick={this.resetYears}
                    >
                      重置
                    </Button>
                    <Button
                      style={{ backgroundColor: "#1A8CFF", color: "#fff" }}
                      className={styles["filter-opt-btn"]}
                      onClick={this.handleConfirm}
                    >
                      确认
                    </Button>
                  </View> */}
                </View>
              </DropdownMenu.Item>
              <DropdownMenu.Item title="学历层次">
                <ScrollView
                  scrollY
                  style={{
                    height: "100%"
                  }}
                >
                  {levelOptions.map(l => (
                    <Cell
                      key={l.value}
                      title={l.text}
                      align="center"
                      clickable
                      onClick={() => this.handleClickLevel(l)}
                      className={clsx(styles["filter-dropdown-cell"], {
                        [styles["checked"]]: l.checked
                      })}
                    >
                      {l.checked && (
                        <Success
                          color="#1A8CFF"
                          style={{
                            fontSize: iconSize
                          }}
                        />
                      )}
                    </Cell>
                  ))}
                </ScrollView>
              </DropdownMenu.Item>
              <DropdownMenu.Item title="院校特色">
                <View className="flex-1 flex flex-col overflow-hidden">
                  <View className={myStyles["dropdown-list-content"]}>
                    <View className="flex-1">
                      <ScrollView
                        scrollY
                        style={{
                          height: "100%"
                        }}
                      >
                        {featureOptions.map(l => (
                          <Cell
                            key={l.value}
                            title={l.text}
                            align="center"
                            clickable
                            onClick={() => this.handleClickFeature_single(l)}
                            className={clsx(styles["filter-dropdown-cell"], {
                              [styles["checked"]]: l.checked
                            })}
                          >
                            {l.checked && (
                              <Success
                                color="#1A8CFF"
                                style={{
                                  fontSize: iconSize
                                }}
                              />
                            )}
                          </Cell>
                        ))}
                      </ScrollView>
                    </View>
                  </View>
                  {/* <View className={styles["filter-opt"]}>
                    <Button
                      color="default"
                      style={{ color: "#666666" }}
                      className={styles["filter-opt-btn"]}
                      onClick={this.resetFeatures}
                    >
                      重置
                    </Button>
                    <Button
                      style={{ backgroundColor: "#1A8CFF", color: "#fff" }}
                      className={styles["filter-opt-btn"]}
                      onClick={this.handleConfirm}
                    >
                      确认
                    </Button>
                  </View> */}
                </View>
              </DropdownMenu.Item>
            </DropdownMenu>
          </View>
        </Sticky>
      </View>
    )
  }
  renderList = () => {
    const { list } = this.state
    const len = list.length
    return (
      <View className="flex flex-col bg-hex-fff mt-20px pt-49px pb-47px pl-30px pr-32px">
        {list.length > 0 ? (
          list.map((l, index) => {
            return (
              <View
                key={l.id}
                className={clsx({
                  "mb-46px": index !== len - 1
                })}
              >
                <GpIntroBadgeItem introItem={l} />
              </View>
            )
          })
        ) : (
          <GpEmpty description="暂无数据" />
        )}
      </View>
    )
  }
  /** 快捷导航 */
  renderJumpNavs = () => {
    return (
      <View className="">
        {/* mt-20px */}
        <GpJumpNavs />
      </View>
    )
  }
  renderListTip = () => {
    const { list } = this.state
    if (list.length === 0) return null
    return (
      <View className="text-center yahei font-normal text-26px text-hex-666 leading-60px">
        暂无更多信息，看看别的内容吧~
      </View>
    )
  }
  render(): React.ReactNode {
    const { showLoading } = this.state
    return (
      <GpContainer className="intro-badge">
        <View>
          {/* 顶部filter */}
          {this.renderFixedFilter()}
          {/* placeholoder */}
          {/* <View className="pt-204px"></View> */}
          {/* 列表 */}
          {this.renderList()}
          {showLoading ? (
            <GpScrollLoading />
          ) : (
            <React.Fragment>
              {this.renderListTip()}
              {/* 快捷导航 */}
              {this.renderJumpNavs()}
              {/* 当前位置 */}
              <GpCurrentPort ports={ports} />
            </React.Fragment>
          )}
        </View>
        {/* 底部导航 */}
        <GpSimpleTabbar />
      </GpContainer>
    )
  }
}
export default IntroBadge
